package activity

import (
	"OnlineRetailers/controllers/admin/PageNum"
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetActivity struct {
	beego.Controller
}

func (c *GetActivity) GetActivity() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Activity/GetActivity"
	res := resMes.GetActivity{}
	activitys := []*Admin.Activity{}
	log := &error2.Log{}
	//mes := &error2.Mes{}
	var err error
	o := orm.NewOrm()

	Page, err := c.GetInt("Page", 0)
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	fmt.Println(begin)
	//sql := "select * from `activity`,`classification` Limit ?,?"
	//_, err = o.Raw(sql, begin, begin+models.DateLength).QueryRows(&activitys)
	_, err = o.QueryTable("Activity").Limit(models.AdminPage, models.AdminPage*Page).OrderBy("-ActivityId").All(&activitys)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql := "select * from `activity_classifications` left join `classification` on classification.classification_id=activity_classifications.classification_id where activity_classifications.activity_id=?"
	for i := 0; i < len(activitys); i++ {

		_, err = o.Raw(sql, activitys[i].ActivityId).QueryRows(&activitys[i].Classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}
	count, err := PageNum.GetPageNum("activity", o)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, "GetPageNum"+err.Error())
		return
	}
	res.Count = count / models.AdminPage
	res.Activity = activitys
	res.Code = "200"
	c.Data["json"] = res

}
